package cn.yunhe.servlet;

import cn.yunhe.entity.Admin;
import cn.yunhe.entity.Block;
import cn.yunhe.entity.News;
import cn.yunhe.service.NewsService;
import cn.yunhe.util.DateUtil;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

@WebServlet("/AddNewsServlet")
public class AddNewsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Admin admin = (Admin) request.getSession().getAttribute("admin");

        SmartUpload sm = new SmartUpload();
        javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory();
        PageContext pageContext = _jspxFactory.getPageContext(this, request, response,
                null, true, 8192, true);
        sm.initialize(pageContext);
        sm.setCharset("UTF-8");
        try {
            sm.upload();
            sm.save("/upfiles");
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

        Request req = sm.getRequest();
        String title = req.getParameter("title");
        String context = req.getParameter("context");
        String writeTime = DateUtil.getCurrTime();

        String pic = sm.getFiles().getFile(0).getFileName();
        int blockid = Integer.parseInt(req.getParameter("blockid"));
        Block block = new Block();
        block.setBlockid(blockid);

        News n = new News();
        n.setTitle(title);
        n.setContext(context);
        n.setWriteTime(writeTime);
        n.setPic(pic);
        n.setBlock(block);
        n.setAdmin(admin);

        NewsService newsService = new NewsService();
        newsService.addNews(n);

        response.sendRedirect("main.html");


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
